package org.springframework.samples.petclinic.system;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.*;


@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {

	/**
	 * 登录session key
	 */
	public static final String SESSION_KEY = "user";
	public static final String TYPE = "TYPE";
	@Bean
	public SecurityInterceptor getSecurityInterceptor() {
		return new SecurityInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());

		// 排除配置
		addInterceptor.excludePathPatterns("/error");
		addInterceptor.excludePathPatterns("/adminLogin**");
		addInterceptor.excludePathPatterns("/entrance**");
		addInterceptor.excludePathPatterns("/ownerLogin**");

		// 拦截配置
		addInterceptor.addPathPatterns("/**");
	}

	private static class SecurityInterceptor implements HandlerInterceptor {


		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
			HttpSession session = request.getSession();
			String uri = request.getRequestURI();
			if (session.getAttribute(SESSION_KEY)!=null) {
				Integer clientType = (Integer) session.getAttribute(WebSecurityConfig.TYPE);
				if (clientType.equals(ClientType.USER_TYPE)){
					if (uri.matches("^/usr/.*")) return true;
					else  {
						String url = "/adminLogin";
						response.sendRedirect(url);
						return false;
					}
				}
				else if (clientType.equals(ClientType.ADMIN_TYPE)) return true;
				else if (clientType.equals(ClientType.VET_TYPE)){
					if (uri.matches("^/vet/.*")) return true;
					else {
						String url = "/adminLogin";
						response.sendRedirect(url);
						return false;
					}
				}
				else return false;
			}
			// 跳转登录
			else {
				String url = "/entrance";
				response.sendRedirect(url);
				return false;
			}
		}
	}
}
